package com.niodata.dp.util;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

/**
 * Created by ndp on 17-3-9.
 */
public class MD5Util {

  private static final String[] hexDigits =
        new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
          "a", "b", "c", "d", "e", "f"};
  private static final int password_length = 8;

  private static final char[] chars = new char[]{'@', '$', '&', '#', '!', ':', ')', '('};

  public static String encode(String input) {
    return encodeByMD5(input);
  }

  /**
   * generate mysql password.
   *
   * @param str source str
   * @return password
   */
  public static String genMysqlPassword(String str) {
    String password = encode(str);
    if (password.length() < password_length) {
      StringBuffer sbu = new StringBuffer(password);
      for (int i = 0; i < password_length - password.length(); i++) {
        sbu.append(chars[i]);
      }
      password = sbu.toString();
    } else {
      int hash1 = Math.abs(password.hashCode());
      int hash2 = Math.abs(str.hashCode());
      char char1 = chars[hash1 % chars.length];
      char char2 = chars[hash2 % chars.length];
      password = password.substring(0, password_length - 2);
      password = char1 + password + char2;
    }
    return password;
  }

  private static String encodeByMD5(String origin) {
    if (origin != null) {
      try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] results = md.digest(origin.getBytes(StandardCharsets.UTF_8));
        String resultString = byteArrayToHexString(results);
        return resultString.toUpperCase();
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    }
    return null;
  }


  private static String byteArrayToHexString(byte[] bytes) {
    StringBuilder result = new StringBuilder();
    for (byte b : bytes) {
      result.append(byteToHexString(b));
    }
    return result.toString();
  }

  private static String byteToHexString(byte b) {
    int n = b;
    if (n < 0) {
      n = 256 + n;
    }
    int d1 = n / 16;
    int d2 = n % 16;
    return hexDigits[d1] + hexDigits[d2];
  }

}
